#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
片段服务
处理录制片段的创建和管理
"""

import os
import uuid
import subprocess
from pathlib import Path
from typing import Dict, Any
from datetime import datetime


class SegmentService:
    """片段服务"""
    
    def __init__(self):
        # 从配置获取路径
        from app.core.config import settings
        self.recording_path = settings.RECORDING_PATH
        self.ffmpeg_path = settings.FFMPEG_PATH
        
        # 确保路径是绝对路径
        self.recording_path = os.path.abspath(self.recording_path)
        
        # 确保目录存在
        Path(self.recording_path).mkdir(parents=True, exist_ok=True)
    
    def _sanitize_filename(self, filename: str) -> str:
        """清理文件名"""
        import re
        # 移除危险字符
        filename = re.sub(r'[<>:"|?*\x00-\x1f]', '', filename)
        filename = filename.replace('..', '').replace('/', '').replace('\\', '')
        return filename.strip()
    
    def _get_ffmpeg_command(self) -> str:
        """获取FFmpeg可执行文件路径"""
        if os.path.isfile(self.ffmpeg_path):
            return f'"{self.ffmpeg_path}"'
        else:
            return "ffmpeg"
    
    def segment_recording(self, recording_path: str, start_time: float, 
                         duration: float, output_name: str = None) -> Dict[str, Any]:
        """从录制文件中提取片段"""
        if not os.path.exists(recording_path):
            raise FileNotFoundError(f"录制文件不存在: {recording_path}")
        
        # 清理输出文件名
        safe_output_name = self._sanitize_filename(output_name or str(uuid.uuid4()))
        
        # 构建输出目录
        output_dir = os.path.join(os.path.dirname(recording_path), "segments")
        output_path = os.path.join(output_dir, f"{safe_output_name}.mp4")
        
        # 确保输出目录存在
        Path(output_dir).mkdir(parents=True, exist_ok=True)
        
        ffmpeg_cmd = self._get_ffmpeg_command()
        
        # 构建提取片段命令
        command = [
            ffmpeg_cmd,
            "-ss", str(start_time),
            "-i", recording_path,
            "-t", str(duration),
            "-c", "copy",
            "-avoid_negative_ts", "make_zero",
            output_path
        ]
        
        # 执行命令
        result = subprocess.run(command, capture_output=True, text=True)
        
        if result.returncode != 0:
            raise RuntimeError(f"FFmpeg错误: {result.stderr}")
        
        # 获取文件信息
        file_size = os.path.getsize(output_path)
        
        return {
            "segment_id": safe_output_name,
            "input_file": recording_path,
            "output_file": output_path,
            "start_time": start_time,
            "duration": duration,
            "file_size": file_size,
            "created_at": datetime.now().isoformat(),
            "status": "completed"
        }